﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AteneoLibriBusinessLogic.Entities;

namespace AteneoLibriBusinessLogic.DAL
{
    public class RecoveryCodeFacade
    {

        AteneoLibriEntityFramework.AteneoLibriEntities db = new AteneoLibriEntityFramework.AteneoLibriEntities();

        public bool insertRecoveryRow(RecoveryCode recovery)
        {
            bool result = true;
            AteneoLibriEntityFramework.RecoveryCode recoveryEF = TOA.RecoveryBookAssembler.DeAssembler(recovery);

            try
            {
                db.RecoveryCodes.AddObject(recoveryEF);
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                result = false;
            }

            return result;
        }

        public Guid getUserByRecoveryCode(string recoveryCode)
        {
            return db.RecoveryCodes.Where(x => x.GeneratedCode == recoveryCode).First().UserId;
        }

        public bool deleteRecoveryCode(Guid userId)
        {
            bool result = false;
            List<AteneoLibriEntityFramework.RecoveryCode> codes = db.RecoveryCodes.Where(x => x.UserId == userId).ToList();

            try
            {
                foreach (var item in codes)
                {
                    db.RecoveryCodes.DeleteObject(item);                    
                }
                db.SaveChanges();
                result = true;
            }
            catch (Exception ex)
            {
                result = false;
            }

            return result;
        }
    }
}
